//
//  ExampleWeiboAPIViewController.m
//  ShareKit
//
//  Created by 凯 赵 on 12-5-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ExampleWeiboAPIViewController.h"
#import "ShareKitAppDelegate.h"

#import "SHKSinaWeiBoV2.h"
#import "SHKQQWeiBoV2.h"
#import "SHKInstagramV2.h"
#import "SHKTumblrV2.h"

@interface ExampleWeiboAPIViewController ()

@end

@implementation ExampleWeiboAPIViewController
@synthesize labelAPI;
@synthesize textFieldResponse;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    CGRect messageRect = CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height-60);
    textFieldResponse = [[UITextView alloc] initWithFrame:messageRect];
    textFieldResponse.editable = NO;
    textFieldResponse.font = [UIFont systemFontOfSize:13];
    textFieldResponse.delegate = self;   
    [self.view addSubview:textFieldResponse];
    
    labelAPI.text=@"";
}

- (void)viewDidUnload
{
    [self setLabelAPI:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.textFieldResponse = nil;
}

- (void)dealloc{

    [textFieldResponse release];
    [labelAPI release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)testRequest
{
    
    textFieldResponse.text=@"";
    // NSString* apiPath = labelAPI.text;
    //https://api.weibo.com/2/statuses/public_timeline.json
    
    //http://open.weibo.com/wiki/2/statuses/upload
    //https://api.weibo.com/2/statuses/update.json
    
     NSString* apiPath=@"statuses/public_timeline.json";
    //NSString* apiPath =@"statuses/update.json";
    
    if (![apiPath length]) {
        return;
    }
    NSLog(@"%@",apiPath);
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            //@"base_app", @"1",
                            //@"dfsf2012e的", @"status",
                            //[params setObject:self.accessToken forKey:@"access_token"];
                            nil];
    
    //[params setObject: @"test2012年活了" forKey:@"status"];
    
    MKNetworkOperation* op= [[SinaWeiBoV2 sharedInstance] requestAPI:apiPath
                                                            httpMethod:@"GET"
                                                                params:params
                                                        onCompletion:^(NSDictionary* responseData){
                                                            //dosomething
                                                            NSLog(@"success");
                                                            
                                                        }onError:^(NSDictionary* responseData, NSError *error){
                                                            //dosomething
                                                            NSLog(@"error");
                                                            
                                                        }];
    
    //
}

- (void)testPostRequest
{
    
    textFieldResponse.text=@"";
    // NSString* apiPath = labelAPI.text;
    //https://api.weibo.com/2/statuses/public_timeline.json
    
    //http://open.weibo.com/wiki/2/statuses/upload
    //https://api.weibo.com/2/statuses/update.json
    
    //NSString* apiPath=@"comments/create.json";
    //NSString* apiPath =@"statuses/update.json";
    //NSString* apiPath=@"statuses/public_timeline.json";
    NSString* apiPath=@"statuses/user_timeline.json";
    
    if (![apiPath length]) {
        return;
    }
    NSLog(@"%@",apiPath);
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            //@"base_app", @"1",
                           // @"我擦，很dddddd牛拜拜的", @"comment",
                            @"2574756487",@"id",
                            //[params setObject:self.accessToken forKey:@"access_token"];
                            nil];
    
    //name = "\U7fca\U5b9d\U7684";
    //[params setObject: @"test2012年活了" forKey:@"status"];
    
    MKNetworkOperation* op= [[SinaWeiBoV2 sharedInstance] requestAPI:apiPath
                                                            httpMethod:@"GET"
                                                                params:params
                                                          onCompletion:^(NSDictionary* responseData){
                                                              //dosomething
                                                              NSLog(@"success");
                                                              
                                                          }onError:^(NSDictionary* responseData, NSError *error){
                                                              //dosomething
                                                              NSLog(@"error");
                                                              //NSLog(@"%@",responseData);
                                                              NSString *errINfo = [NSString stringWithFormat:@"%@ %@",responseData,[error localizedDescription]];
                                                          }];
    
}
- (void)testSendWeibo
{
    MKNetworkOperation* op=[[SinaWeiBoV2 sharedInstance] update:@"testoudoudofuosdufodisf22aia哈哈"
                                                            image:[UIImage imageNamed:@"sanFran.jpg"]
                                                     onCompletion:^(NSDictionary* responseData){
                                                         //dosomething
                                                         NSLog(@"success");
                                                         NSLog(@"%@",responseData);
                                                         self.textFieldResponse.text =responseData;
                                                         
                                                        // bool finished =[op isFinished];
                                                         
                                                     }onError:^(NSDictionary* responseData, NSError *error){
                                                         //dosomething
                                                         NSLog(@"error");
                                                         NSLog(@"%@",responseData);
                                                         NSString *errINfo = [NSString stringWithFormat:@"%@ %@",responseData,[error localizedDescription]];
                                                         self.textFieldResponse.text =errINfo;//responseData;
                                                     } ];
    
    bool finished =[op isFinished];
    
}

- (void)testSendQQWeibo
{
    MKNetworkOperation* op= [ [QQWeiBoV2 sharedInstance]  update:@"hello, 腾讯微薄 withs pic"
                                                           image:[UIImage imageNamed:@"1.JPG"]
                                                    onCompletion:^(NSDictionary* responseData){
                                                        //dosomething
                                                        NSLog(@"success");
                                                    }onError:^(NSDictionary* responseData, NSError *error){
                                                        //dosomething
                                                        NSLog(@"error");
                                                    }];
}
-(void) testTumblr
{
    if (![[TumblrV2 sharedInstance]autologin]) {
        return;
    }
    
    /*
     Blog: get blog data or write to a blog
     api.tumblr.com/v2/blog/{base-hostname}/...
     /info  
     http://api.tumblr.com/v2/blog/david.tumblr.com/info?api_key={key}
     /avatar
     /followers
     /posts
     http://api.tumblr.com/v2/blog/peacecorps.tumblr.com/posts/photo?notes_info=true
     
     User: get user data or perform user actions
     api.tumblr.com/v2/user/...
     
     /user/dashboard
     /user/likes
     /user/following
     */
    
    //NSString* requestPath = @"blog/yuankan.tumblr.com/posts/text";
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"2", @"limit",
                            @"photo", @"type",
                            //[params setObject:self.accessToken forKey:@"access_token"];
                            nil];
    
    NSString* requestPath =@"user/dashboard";
    MKNetworkOperation* op = [[TumblrV2 sharedInstance ]requestAPI:requestPath 
                                                        httpMethod:@"GET" params:params 
                                                      onCompletion:^(NSDictionary *responseData) {
                                                          NSLog(@"tumblr getit");
                                                          NSLog(@"success");
                                                          NSLog(@"%@",responseData);
                                                      } onError:^(NSDictionary *responseData, NSError *error) {
                                                          NSLog(@"tumblr test error");
                                                      }];
}
- (void)testInstgram
{
    if (![[InstagramV2 sharedInstance] autologin]) {
        return ;
    }
    
    textFieldResponse.text=@"";
    // NSString* apiPath = labelAPI.text;
    
    //https://api.instagram.com/v1/media/popular
    //http://instagr.am/developer/endpoints/
    /*
     正确回应：
     {
     "meta": {
     "code": 200
     },
     "data": {
     ...
     },
     "pagination": {
     "next_url": "...",
     "next_max_id": "13872296"
     }
     }
     错误回应：
     {
     "meta": {
     "error_type": "OAuthException",
     "code": 400,
     "error_message": "..."
     }
     }
     请求下一段数据
     {
     ...
     "pagination": {
     "next_url": "https://api.instagram.com/v1/tags/puppy/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&max_id=13872296",
     "next_max_id": "13872296"
     }
     }
     */
    
    
    //NSString* apiPath=@"media/popular";
    //https://api.instagram.com/v1/tags/snow/media/recent?access_token=753501.f59def8.b883f650c50f4e0d8fe41e699c7e1803
    NSString* apiPath=@"tags/美/media/recent";//snow 为tag，tag相关内容
   // NSString* apiPath=@"tags/美";//snow 为tag,tag相关内容的个数
    NSString* apiEncode = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)apiPath, nil, nil, kCFStringEncodingUTF8);
    apiPath = apiEncode;
    
    //https://api.instagram.com/v1/tags/nofilter?access_token=753501.f59def8.b883f650c50f4e0d8fe41e699c7e1803
    
    if (![apiPath length]) {
        return;
    }
    NSLog(@"%@",apiPath);
    
    //支持参数："count", "max_id"
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"20", @"count",
                            //@"13872296",@"max_id",//见上文注释next_max_id
                            nil];
    
    NSLog(@"start");
    
    MKNetworkOperation* op= [[InstagramV2 sharedInstance] requestAPI:apiPath
                                                          httpMethod:@"GET"
                                                              params:params
                                                        onCompletion:^(NSDictionary* responseData){
                                                            //dosomething
                                                            NSLog(@"success");
                                                            int code = [[[responseData objectForKey:@"meta"] objectForKey:@"code"]intValue];
                                                            if (code ==200) {
                                                                NSLog(@"%@",[[[responseData objectForKey:@"data"] class] description]);
                                                                NSArray * array = [responseData objectForKey:@"data"];
                                                                int count =[array count];
                                                                NSLog(@"count:%d",count);
                                                                for (int i=0; i<count; i++) {
                                                                    NSDictionary* temp= [array objectAtIndex:i];
                                                                    //NSLog(@"low:%@",[[[temp objectForKey:@"images"]objectForKey:@"low_resolution"]objectForKey:@"url"]);
                                                                    NSLog(@"%@",[[temp objectForKey:@"caption"]objectForKey:@"text"]);
                                                                    NSLog(@"standard:%@%@",[[[temp objectForKey:@"images"]objectForKey:@"standard_resolution"]objectForKey:@"url"],@"?access_token=2.00Xd4ibCdiHuUCcc0f1cb762jVvXLB");
                                                                    //NSLog(@"thumbnail:%@%@",[[[temp objectForKey:@"images"]objectForKey:@"standard_resolution"]objectForKey:@"url"],@"?access_token=2.00Xd4ibCdiHuUCcc0f1cb762jVvXLB");
                                                                }
                                                                NSLog(@"end");

                                                            }
                                                            
                                                        }onError:^(NSDictionary* responseData, NSError *error){
                                                            //dosomething
                                                            NSLog(@"error");
                                                            //NSLog(@"%@",responseData);
                                                            NSString *errINfo = [NSString stringWithFormat:@"%@ %@",responseData,[error localizedDescription]];
                                                        }];
}
- (IBAction)Get:(UIButton *)sender {
    //[self testRequest];
   // [self testSendWeibo];
    [self testPostRequest];
}

- (IBAction)choseAPI:(UIButton *)sender {
   // [self testRequest];
    //[self testPostRequest];
   // [self testSendQQWeibo];
    
   // [self testInstgram];
    
    [self testTumblr];
}
@end
